package com.alliky.user.ui.activiry

import com.alibaba.android.arouter.facade.annotation.Route
import com.alliky.common.entity.MessageEvent
import com.alliky.common.entity.User
import com.alliky.common.global.Global
import com.alliky.common.router.Router
import com.alliky.common.utils.clickWithTrigger
import com.alliky.core.base.BaseActivity
import com.alliky.core.manage.UserManage
import com.alliky.home.mvp.contract.LoginContract
import com.alliky.home.mvp.presenter.LoginPresenter
import com.alliky.user.R
import kotlinx.android.synthetic.main.activity_login.*
import org.greenrobot.eventbus.EventBus

@Route(path = Router.User.Activity.LoginActivity)
class LoginActivity : BaseActivity<LoginContract.View, LoginContract.Presenter>(),
    LoginContract.View {

    override fun createPresenter(): LoginContract.Presenter = LoginPresenter()

    override fun setLayout(): Any? = R.layout.activity_login

    override fun initData() {
    }

    override fun initView() {
        super.initView()
        btn_login.clickWithTrigger {
            if (getUserName().isNullOrBlank()) {
                showError("用户名不能为空")
                return@clickWithTrigger
            }

            if (getPassword().isNullOrBlank()) {
                showError("密码不能为空")
                return@clickWithTrigger
            }

            mPresenter?.doLogin(getUserName(), getPassword())
        }
    }

    fun getUserName(): String {
        return et_username.text.toString().trim()
    }

    fun getPassword(): String {
        return et_password.text.toString().trim()
    }

    override fun loginSuccess(user: User) {
        user?.let {
            showMessage("登录成功")
            UserManage.instance?.setUser(user)
            EventBus.getDefault().post(MessageEvent(Global.CODE.LOGIN_SUCCESS))
            finish()
        }
    }
}